<script>
import * as types from '@/store/types';
import config from 'config';
import * as helps from '@/utils/helps';
import DataTree from './DataTree';
import { date } from '@ktw/ktools';

export default {
  name: 'MapAdd',
  components: { DataTree },
  props: {
    mapId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      newLayer: false,
      serviceData: [],
      subjectData: [],
      layerKeyword: '',
      layerColumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
        },
        {
          title: '服务名称',
          key: 'title',
        },
        {
          title: '类型',
          key: 'serviceType',
        },
        {
          title: '时间',
          key: 'time',
        },
      ],
      layerData: [],
      layerTotal: 0,
      pageInited: true,
      tableLoading: false,
    };
  },
  computed: {
    ogcLayers() {
      if (this.$store.state[this.mapId]) {
        return this.$store.getters[this.mapId + '/ogcLayers'];
      } else {
        return [];
      }
    },
    subjectLayer() {
      if (this.$store.state[this.mapId]) {
        return this.$store.getters[this.mapId + '/subjectLayer'];
      } else {
        return [];
      }
    },
  },
  watch: {
    ogcLayers(newVal) {
      this.setLayerGroup(newVal);
    },
    subjectLayer(newVal) {
      this.setSubLayerGroup(newVal);
    },
  },
  mounted() {
    this.setLayerGroup(this.ogcLayers);
    this.setSubLayerGroup(this.subjectLayer);
  },
  methods: {
    // 判断图层对象类型
    getLayerObjectType(layers) {
      if (layers instanceof L.NonTiledLayer.WMS) {
        return 12;
      }
    },
    // 请求服务
    async findAllServices(options) {
      // 服务类型 5,10,11,12,21,22,23
      this.tableLoading = true;
      const response = await api.portal.findServiceList(options);
      this.layerData = [];
      response.data.dataSource.forEach(item => {
        if (item.serviceUrl !== '' && item.serviceType === '12') {
          this.layerData.push({
            title: item.title,
            name: item.name,
            serviceType: item.serviceType,
            serviceUrl: item.serviceUrl,
            crs: item.crs,
            time: helps.getLocalTime(item.createTime),
          });
        }
      });
      this.tableLoading = false;
      // 分页总数要重新设置
      if (this.pageInited) {
        this.layerTotal = response.data.pageInfo.totalCount;
      }
    },
    // 类型配置
    getServiceType(item) {
      const serviceType = {
        '12': 'WMS',
      };
      return serviceType[item];
    },
    // TODO: 分类浏览服务，目前查询了类型为12的服务，同时，此处没有目录id
    addMapLayers(
      title = '',
      pageCount = { pageIndex: 1, pageSize: 10 },
      catalogId = config.datavfunction.catalogId
    ) {
      if (typeof title === 'object') title = '';
      this.newLayer = true;
      const options = {
        objCondition: {
          orgId: this.$user.orgid,
          catalogId, // 目录id（必填）
          ownerId: this.$user.orgid, // 拥有者id（必填）
          getall: 'all', // 递归查数据（必填）
          serviceType: '12', // 服务类型（选填）
          title,
        },
        ...pageCount,
        orderby: 'createTime_desc', // 排序（选填）
      };
      this.findAllServices(options);
    },
    selectTree(data) {
      if (this.newLayer) {
        this.pageInited = true;
        this.childId = data.childId;
        this.addMapLayers(
          '',
          {
            pageIndex: 1,
            pageSize: 10,
          },
          data.childId
        );
      }
    },
    selectLayers(layerData) {
      this.addLayerData = layerData;
    },
    // 添加新的图层
    addNewLayers() {
      this.newLayer = false;
      const addWmslayers = {};
      this.addLayerData.forEach(layers => {
        this.serviceData.push(layers);
        const url = new URL(layers.serviceUrl);
        const layersName = url.searchParams.get('layers');
        addWmslayers[layersName] = [];
        addWmslayers[layersName].push({
          servicestype: +layers.serviceType,
          servicesurl: layers.serviceUrl,
          title: layersName,
        });
      });
      // 处理成地图组件加载图层的数据格式
      this.$emit('on-addlayers', addWmslayers);
    },
    // 添加底图图层
    addBaseLayers() {},
    // 添加专题图层
    addSubjectLayers() {
      this.$emit('on-setMapData', 'data');
    },
    // 图层管理
    setLayerGroup(newVal) {
      this.serviceData = [];
      if (newVal.length !== 0) {
        newVal.forEach(layers => {
          this.serviceData.push({
            name: layers.options.layers,
            serviceType: this.getLayerObjectType(layers),
            layers,
          });
        });
      }
    },
    setSubLayerGroup(newVal) {
      this.subjectData = [];
      newVal.forEach(layers => {
        this.subjectData.push({
          name: layers.options.layers,
          types: layers.options.type,
          layers,
        });
      });
    },
    // 设置图层在浏览范围
    setLayerToView(layers) {
      this.$emit('on-setLayerToView', layers);
    },
    // 删除图层
    removeLayer(layers) {
      const currentId = this.$store.getters.currentId;
      this.$store.commit(this.mapId + '/SET_MAP_GOCLAYER_DELETE', [layers.layers.options.layers]);
      const mapData = this.$store.getters.controls[currentId];
      mapData.options.TileWMSLayer.data = this.$store.state[this.mapId].serviceList;
      this.$store.commit(types.UPDATE_CHART_CONFIG, {
        data: { [currentId]: mapData },
      });
    },
    // 图层编辑
    goToMapEdit(layers) {
      this.$emit('on-edit-subjectlayer', layers);
    },
    removeSubLayer(layers) {
      this.$store.commit(types.DELETE_SUBJECTLAYER_DATA, {
        types: layers.types,
        name: layers.name,
      });
    },
    // 搜索
    searchLayer(title) {
      this.pageInited = true;
      this.addMapLayers(this.layerKeyword, {
        pageIndex: 1,
        pageSize: 10,
      });
    },
    // 分页
    querylayers(pageIdx) {
      this.pageInited = false;
      const pageCount = {
        pageIndex: pageIdx,
        pageSize: 10,
      };
      if (this.childId) {
        this.addMapLayers('', pageCount, this.childId);
      } else {
        this.addMapLayers('', pageCount);
      }
    },
  },
};
</script>

<template>
  <div class="datav-map-add">
    <div class="map-layers">
      <div class="layer-type">
        <p>底图</p>
        <span>添加底图，编辑底图进行浏览</span>
        <Icon
          type="plus-round"
          size="16"
          @click.native="addBaseLayers"></Icon>
      </div>
      <div class="datasheet-content">
      </div>
    </div>
    <div class="map-layers">
      <div class="layer-type">
        <p>覆盖图层</p>
        <span>添加不同类型的服务做图层浏览</span>
        <Icon
          type="plus-round"
          size="16"
          @click.native="addMapLayers"></Icon>
      </div>
      <div class="datasheet-content">
        <Row>
          <Card
            v-for="item in serviceData"
            :key="item.id"
            draggable="true">
            <div class="service-type">
              <span class="overlayer">{{ getServiceType(item.serviceType) }}</span>
              <span>{{ item.name }}</span>
              <div class="layer-mamager">
                <Tooltip
                  content="缩放到视图范围"
                  placement="top">
                  <Icon
                    type="arrow-right-c"
                    size="18"
                    @click.native="setLayerToView(item)"></Icon>
                </Tooltip>
                <Tooltip
                  content="属性查询"
                  placement="top">
                  <Icon
                    type="ios-search-strong"
                    size="18"></Icon>
                </Tooltip>
                <Tooltip
                  :transfer="true"
                  content="删除图层"
                  placement="top">
                  <Icon
                    type="trash-b"
                    size="18"
                    @click.native="removeLayer(item)"></Icon>
                </Tooltip>
              </div>
            </div>
          </Card>
        </Row>
      </div>
    </div>
    <div class="map-layers">
      <div class="layer-type">
        <p>专题图层</p>
        <span>地图功能、可视化展示数据</span>
        <Icon
          type="plus-round"
          size="16"
          @click.native="addSubjectLayers"></Icon>
      </div>
      <div class="datasheet-content">
        <Row>
          <Card
            v-for="(item,index) in subjectData"
            :key="index"
            draggable="true">
            <div class="service-type">
              <span class="subject">{{ item.types }}</span>
              <span>{{ item.name }}</span>
              <div class="layer-mamager">
                <Tooltip
                  content="缩放到视图范围"
                  placement="top">
                  <Icon
                    type="arrow-right-c"
                    size="18"
                    @click.native="setLayerToView(item)"></Icon>
                </Tooltip>
                <Tooltip
                  content="图层编辑"
                  placement="top">
                  <Icon
                    type="edit"
                    size="18"
                    @click.native="goToMapEdit(item)"></Icon>
                </Tooltip>
                <Tooltip
                  :transfer="true"
                  content="删除图层"
                  placement="top">
                  <Icon
                    type="trash-b"
                    size="18"
                    @click.native="removeSubLayer(item)"></Icon>
                </Tooltip>
              </div>
            </div>
          </Card>
        </Row>
      </div>
    </div>
    <!-- 添加叠加图层-->
    <Modal
      v-model="newLayer"
      class="datav-mapadd-modal"
      width="830"
      @on-ok="addNewLayers">
      <div class="modal-title">
        <p>图层搜索</p>
        <Input
          v-model="layerKeyword"
          placeholder="输入服务名称..."
          style="width: 500px"
          @on-change="searchLayer"></Input>
        <Button
          type="primary"
          @click="searchLayer">查询</Button>
      </div>
      <div class="modal-title">
        <p>图层选择</p>
        <div class="res-data-wrapper">
          <DataTree
            :click-node-expand="false"
            directory
            accordion
            @on-current-select="selectTree">
          </DataTree>
          <Table
            :columns="layerColumns"
            :data="layerData"
            :loading="tableLoading"
            height="350"
            size="small"
            highlight-row
            stripe
            border
            @on-selection-change="selectLayers"></Table>
        </div>
      </div>
      <div class="layer-table-page">
        <Page
          :total="layerTotal"
          size="small"
          show-total
          @on-change="querylayers">
        </Page>
      </div>
    </Modal>
  </div>
</template>

<style lang="less" scoped>
.datav-map-add {
  width: 100%;
  height: 100%;
}

.datav-mapadd-modal {
  .modal-title {
    p {
      height: 30px;
      line-height: 30px;
    }
    .res-data-wrapper {
      display: flex;
    }
    .k-datatree {
      width: 150px;
    }
    .k-table-wrapper {
      flex: 1;
    }
  }
  /deep/ .k-table {
    height: 350px;
    overflow-y: auto;
    overflow-x: hidden;
  }
  .layer-table-page {
    text-align: right;
    margin-top: 10px;
  }
}

.datasheet-content {
  .k-card {
    background-color: #f5f7fa;
    cursor: pointer;

    /deep/ .k-card-body {
      padding: 10px 15px;
    }

    /deep/ .service-type {
      span:first-child {
        display: inline-block;
        padding: 2px 4px;
        background-color: #20a1ff;
        color: #fff;
        font-size: 6px;
      }

      .overlayer {
        background-color: #20a1ff !important;
      }

      .subject {
        background-color: #72d8b1 !important;
      }

      .layer-mamager {
        float: right;

        .k-icon {
          padding-left: 5px;
        }
        .k-icon:hover {
          color: #20a1ff;
        }
      }
    }
  }
}

.map-layers {
  .layer-type {
    position: relative;
    border-bottom: 1px solid #eee;

    p {
      margin-top: 10px;
      margin-left: 15px;
      padding-left: 5px;
      line-height: 30px;
      height: 30px;
      color: #20a1ff;
      font-size: 14px;
      border-left: 2px solid #20a1ff;
    }

    span {
      padding-left: 22px;
      font-size: 10px;
      color: #777;
    }

    .k-icon {
      position: absolute;
      top: 8px;
      right: 15px;
      cursor: pointer;
    }
  }
}
</style>
